package com.hk.core.security.cas.oauth2.authentication;

import com.hk.commons.util.ConverterUtils;
import com.hk.commons.util.JsonUtils;
import com.hk.core.authentication.api.UserPrincipal;
import com.hk.core.authentication.security.SecurityUserPrincipal;
import com.hk.core.authentication.security.authentication.accesstoken.TokenRequestMatcher;
import com.hk.core.security.cas.oauth2.CasOauth2Properties;
import com.hk.core.web.client.RestTemplates;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationConverter;

import java.util.Collections;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class CASAuthenticationConverter implements AuthenticationConverter {

    private final TokenRequestMatcher tokenRequestMatcher;

    private final CasOauth2Properties casOauth2Properties;

    @Setter
    private Class<? extends UserPrincipal> principalClass = SecurityUserPrincipal.class;

    @Override
    public Authentication convert(HttpServletRequest request) {
        String token = tokenRequestMatcher.tokenResolve(request);
        String result = RestTemplates.post(casOauth2Properties.getCasServerProfileUrl(), Map.of(casOauth2Properties.getCasServerProfileParamName(), token), String.class);
        log.debug("CAS authentication token:{}, result: {}", token, result);
        CasProfileAuthenticationResult authenticationResult = JsonUtils.deserialize(result, CasProfileAuthenticationResult.class);
        Map<String, Object> attributes = authenticationResult.getAttributes();
        return new CasAuthenticationToken(JsonUtils.deserialize(JsonUtils.serialize(attributes), principalClass)
                .setUserId(ConverterUtils.defaultConvert(attributes.get("id"), Long.class))
                .setAccount(authenticationResult.getId()),
                Collections.emptyList());
    }
}
